1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/*!
Typing universes
*/
use super::*;

/// A term containing a typing universe
#[derive(Debug, Clone)]
pub struct UniverseTerm {
    /// The universe underlying this term
    universe: Universe,
    /// The annotation of this term, if any
    annot: Option<Annotation>,
    /// The code of this term
    code: Code,
    /// The variable filter of this term
    filter: VarFilter,
    /// The pre-computed flags of this term
    flags: AtomicTyckFlags,
}

impl From<Universe> for UniverseTerm {
    #[inline]
    fn from(universe: Universe) -> Self {
        Self::new_unchecked(universe, None)
    }
}

impl UniverseTerm {
    /// Create a new universe term without any type-checking
    #[inline]
    pub fn new_unchecked(universe: Universe, annot: Option<Annotation>) -> UniverseTerm {
        let code = Self::compute_code(&universe, annot.as_ref());
        let filter = Self::compute_filter(&universe, annot.as_ref());
        let flags = Self::compute_flags(&universe, annot.as_ref()).into();
        UniverseTerm {
            universe,
            annot,
            code,
            filter,
            flags,
        }
    }

    /// Compute the code for a universe term with a given optional annotation
    #[inline]
    pub fn compute_code(universe: &Universe, annot: Option<&Annotation>) -> Code {
        let universe_ = 0x756e697665727365; // "universe" in ASCII
        let mut hasher = AHasher::new_with_keys(universe_, 0x0);
        universe.hash(&mut hasher);
        let pre = hasher.finish();
        if let Some(ty) = annot {
            ty.hash(&mut hasher)
        };
        let post = hasher.finish();
        Code::new(pre, post)
    }

    /// Compute the filter for a universe term with a given optional annotation
    #[inline]
    pub fn compute_filter(_universe: &Universe, annot: Option<&Annotation>) -> VarFilter {
        annot.get_filter()
    }

    /// Compute the flags for a universe term with a given optional annotation
    #[inline]
    pub fn compute_flags(_universe: &Universe, annot: Option<&Annotation>) -> TyckFlags {
        TyckFlags::default()
            .with_flag(AnnotTyck, L4::with_true(annot.is_none()))
            .with_flag(LocalTyck, L4::with_true(annot.is_none()))
            .with_flag(GlobalTyck, L4::with_true(annot.is_none()))
    }

    /// Get this term as a universe
    #[inline]
    pub fn as_universe(&self) -> &Universe {
        &self.universe
    }
}

impl Cons for UniverseTerm {
    type Consed = UniverseTerm;

    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self> {
        if let Some(consed_ty) = self.annot.cons(ctx).flatten() {
            let code = Self::compute_code(&self.universe, Some(&consed_ty));
            Some(UniverseTerm {
                universe: self.universe.clone(),
                annot: Some(consed_ty),
                code,
                filter: self.filter,
                flags: self.flags.clone(),
            })
        } else {
            None
        }
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for UniverseTerm {
    type Substituted = UniverseTerm;

    fn subst_rec(&self, ctx: &mut (impl SubstCtx + ?Sized)) -> Result<Option<UniverseTerm>, Error> {
        if !ctx.intersects(self.filter, self.code, Form::BetaEta) {
            return Ok(None);
        }
        let ty = self.annot.subst_rec(ctx)?;
        if let Some(ty) = ty.flatten() {
            let code = UniverseTerm::compute_code(&self.universe, Some(&ty));
            let filter = UniverseTerm::compute_filter(&self.universe, Some(&ty));
            let flags = UniverseTerm::compute_flags(&self.universe, Some(&ty)).into();
            let term = UniverseTerm {
                annot: Some(ty),
                universe: self.universe.clone(),
                code,
                filter,
                flags,
            };
            Ok(Some(term))
        } else {
            Ok(None)
        }
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for UniverseTerm {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        true
    }

    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        if let Some(annot) = &self.annot {
            if let Ok(succ) = self.as_universe().succ() {
                Some(succ.is_subtype_in(&*annot.base(), &mut Structural)? && annot.tyck(ctx)?)
            } else {
                Some(false)
            }
        } else {
            Some(true)
        }
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.flags.load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.flags.set_flags(flags);
    }
}

impl HasDependencies for UniverseTerm {
    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.filter
    }

    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.filter.contains(ix) && (self.filter.exact() || self.annot.has_var_dep(ix, equiv))
    }

    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        if let Some(contains) = self.filter.contains_below(ix, base) {
            contains
        } else {
            self.annot.has_dep_below(ix, base)
        }
    }
}

impl TermEq for UniverseTerm {
    #[inline]
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if let Some(result) =
            ctx.approx_term_eq_code((self.code, Form::BetaEta), (other.code, Form::BetaEta))
        {
            return result;
        }
        Some(
            self.universe == other.universe
                && (!ctx.cmp_annot() || self.annot.eq_in(&other.annot, ctx)?)
                && (!ctx.cmp_var() || self.annot.is_some() == other.annot.is_some()),
        )
    }
}

impl Value for UniverseTerm {
    type ValueConsed = UniverseTerm;
    type ValueSubstituted = UniverseTerm;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Universe(self)
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        if let Some(ty) = &self.annot {
            Some(ty.borrow_annot())
        } else {
            self.universe.annot()
        }
    }

    #[inline]
    fn id(&self) -> Option<NodeIx> {
        None
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<UniverseTerm>, Error> {
        if let Some(annot) = &self.annot {
            if let Some(ty) = ty {
                if let Some(annot) = annot.coerce_ty(&ty, ctx)? {
                    return self.annotate_unchecked(annot, ctx.cons_ctx());
                }
            }
            Ok(None)
        } else {
            self.universe.coerce(ty, ctx)
        }
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<UniverseTerm>, Error> {
        if let Some(curr_annot) = &self.annot {
            if curr_annot.is_sub_annot(&annot) {
                Ok(None)
            } else {
                Ok(Some(UniverseTerm::new_unchecked(
                    self.universe.clone(),
                    Some(annot),
                )))
            }
        } else {
            self.universe.annotate_unchecked(annot, ctx)
        }
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        self.universe.is_subtype_in(other, ctx)
    }

    #[inline]
    fn universe(&self) -> Option<Universe> {
        self.universe.succ().ok()
    }

    #[inline]
    fn code(&self) -> Code {
        self.code
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        self.universe.code()
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        //TODO: optimize
        match other {
            Term::Universe(other) => self.eq_in(other, ctx),
            other if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn form(&self) -> Form {
        Form::BetaEta
    }
}

/// A typing universe
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Universe(u32);

impl Universe {
    /// Try to create a new universe given a level and variable flag
    #[inline]
    pub fn try_new(level: u32, is_var: bool) -> Result<Universe, Error> {
        level
            .checked_mul(2)
            .ok_or(Error::UniverseOutOfBounds)?
            .checked_add(is_var as u32)
            .ok_or(Error::UniverseOutOfBounds)
            .map(Universe)
    }

    /// Get the universe of sets
    #[inline]
    pub fn set() -> Universe {
        Universe(2)
    }

    /// Get a universe containing this one
    #[inline]
    pub fn succ(&self) -> Result<Universe, Error> {
        self.0
            .checked_add(2)
            .ok_or(Error::UniverseOutOfBounds)
            .map(Universe)
    }

    /// Get a universe containing both input universes
    #[inline]
    pub fn join(&self, other: &Universe) -> Universe {
        let level = (self.0 / 2).max(other.0 / 2);
        let is_var = (self.0 % 2).max(other.0 % 2);
        Universe((level * 2) | is_var)
    }

    /// Get the level of this universe
    #[inline]
    pub fn level(&self) -> u32 {
        self.0 / 2
    }

    /// Get whether this universe is a variable
    #[inline]
    pub fn is_var(&self) -> bool {
        self.0 % 2 == 1
    }
}

impl Cons for Universe {
    type Consed = Universe;

    #[inline]
    fn cons(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self> {
        None
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Universe {
    type Substituted = Universe;

    #[inline]
    fn subst_rec(
        &self,
        _ctx: &mut (impl SubstCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error> {
        Ok(None)
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl Typecheck for Universe {
    fn do_local_tyck(&self, _ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        true
    }

    fn do_global_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn do_annot_tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn tyck(&self, _ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        TyckFlags::ALL_TRUE
    }

    #[inline]
    fn set_flags(&self, _flags: TyckFlags) {
        //TODO: check flags are all compatible with ALL_TRUE
    }
}

impl HasDependencies for Universe {
    #[inline]
    fn has_var_dep(&self, _ix: u32, _equiv: bool) -> bool {
        false
    }

    #[inline]
    fn has_dep_below(&self, _ix: u32, _base: u32) -> bool {
        false
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        VarFilter::EMPTY
    }
}

impl TermEq for Universe {
    #[inline]
    fn eq_in(&self, other: &Self, _ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        Some(self.eq(other))
    }
}

impl Value for Universe {
    type ValueConsed = UniverseTerm;
    type ValueSubstituted = UniverseTerm;

    #[inline]
    fn into_term_direct(self) -> Term {
        Term::Universe(self.into())
    }

    #[inline]
    fn annot(&self) -> Option<AnnotationRef> {
        self.succ().ok().map(AnnotationRef::Universe)
    }

    #[inline]
    fn id(&self) -> Option<NodeIx> {
        None
    }

    #[inline]
    fn is_local_ty(&self) -> Option<bool> {
        // Universes are always types
        Some(true)
    }

    #[inline]
    fn is_local_universe(&self) -> Option<bool> {
        Some(true)
    }

    #[inline]
    fn is_local_function(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_local_pi(&self) -> Option<bool> {
        Some(false)
    }

    #[inline]
    fn is_root(&self) -> bool {
        true
    }

    #[inline]
    fn coerce(
        &self,
        ty: Option<TermId>,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<UniverseTerm>, Error> {
        if let Some(ty) = ty {
            if let Some(annot) = self.succ()?.coerce_annot_ty(&ty, ctx)? {
                self.annotate_unchecked(annot, ctx.cons_ctx())
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    #[inline]
    fn annotate_unchecked(
        &self,
        annot: Annotation,
        _ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Result<Option<UniverseTerm>, Error> {
        if let Some(true) = self.succ()?.is_subtype(&*annot.ty()) {
            Ok(None)
        } else {
            Ok(Some(UniverseTerm::new_unchecked(self.clone(), Some(annot))))
        }
    }

    #[inline]
    fn is_subtype_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        //TODO: optimize
        let rooted = ctx.root_mut(other);
        match (other, rooted.as_deref()) {
            (_, Some(Term::Universe(other))) | (Term::Universe(other), _) => {
                Some(self <= other.as_universe())
            }
            _ if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn universe(&self) -> Option<Universe> {
        self.succ().ok()
    }

    #[inline]
    fn code(&self) -> Code {
        let universe = 0x756e697665727365; // "universe" in ASCII
        let mut hasher = AHasher::new_with_keys(universe, 0x0);
        self.0.hash(&mut hasher);
        Code(hasher.finish())
    }

    #[inline]
    fn untyped_code(&self) -> Code {
        self.code()
    }

    #[inline]
    fn eq_term_in(&self, other: &Term, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        match other {
            Term::Universe(other) => UniverseTerm::from(self.clone()).eq_in(other, ctx),
            _ if other.is_root() => Some(false),
            _ => None,
        }
    }

    #[inline]
    fn form(&self) -> Form {
        Form::BetaEta
    }
}

impl Eq for UniverseTerm {}

impl PartialEq for UniverseTerm {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.code == other.code && self.universe == other.universe && self.annot == other.annot
    }
}

impl Hash for UniverseTerm {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.universe.hash(state);
        self.annot.hash(state)
    }
}

impl PartialEq<Term> for UniverseTerm {
    #[inline]
    fn eq(&self, other: &Term) -> bool {
        match other {
            Term::Universe(other) => self.eq(other),
            _ => false,
        }
    }
}

impl PartialEq<TermId> for UniverseTerm {
    #[inline]
    fn eq(&self, other: &TermId) -> bool {
        self.eq(&**other)
    }
}

impl PartialEq<Universe> for UniverseTerm {
    fn eq(&self, other: &Universe) -> bool {
        self.annot.is_none() && self.universe.eq(other)
    }
}

impl PartialEq<UniverseTerm> for Universe {
    fn eq(&self, other: &UniverseTerm) -> bool {
        other.annot.is_none() && other.universe.eq(self)
    }
}

impl PartialEq<Term> for Universe {
    #[inline]
    fn eq(&self, other: &Term) -> bool {
        match other {
            Term::Universe(other) => self.eq(other),
            _ => false,
        }
    }
}

impl PartialEq<TermId> for Universe {
    #[inline]
    fn eq(&self, other: &TermId) -> bool {
        self.eq(&**other)
    }
}

impl Debug for Universe {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if self.is_var() {
            write!(f, "UniverseVar({})", self.level())
        } else {
            write!(f, "Universe({})", self.level())
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    fn test_set_properties(ctx: &mut impl TyCtxMut) {
        let set = Universe::set();

        assert_eq!(set.cons_id(ctx.cons_ctx()), None);
        super::value_test_utils::test_value_invariants(&set, ctx.cons_ctx());
        super::value_test_utils::test_value_invariants(
            &set.clone_into_id_with(ctx.cons_ctx()),
            ctx.cons_ctx(),
        );
        let type_ = set.succ().unwrap();
        assert_eq!(type_.cons_id(ctx.cons_ctx()), None);
        assert_eq!(set.annot(), Some(AnnotationRef::Universe(type_.clone())));
        super::value_test_utils::test_value_invariants(&type_, ctx.cons_ctx());
        super::value_test_utils::test_value_invariants(
            &type_.clone_into_id_with(ctx.cons_ctx()),
            ctx.cons_ctx(),
        );

        let set_type = UniverseTerm::new_unchecked(
            set.clone(),
            Annotation::from_ty(type_.into_id_with(ctx.cons_ctx())).ok(),
        );
        assert_eq!(set_type.tyck(ctx), Some(true));
        let set_cycle = UniverseTerm::new_unchecked(
            set.clone(),
            Annotation::from_ty(set.into_id_with(ctx.cons_ctx())).ok(),
        );
        assert_eq!(set_cycle.tyck(ctx), Some(false));
    }

    #[test]
    fn set_properties() {
        test_set_properties(&mut Trivial::default());
        test_set_properties(&mut DisjointSetCtx::default());
    }
}